let app = getApp();
import utils from '../../utils/util';
const PAGE_SIZE = 30;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    systemInfo: utils.getStorage("systemInfo"),
    // tabList:[{
    //   type:1,
    //   tit:"全部"
    // },{
    //   type:2,
    //   tit:"直播中"
    // },{
    //   type:3,
    //   tit:"直播中"
    // },{
    //   type:4,
    //   tit:"已结束"
    // }],
    // tabIndex:1,
    loadStatus: "",
    loadShopStatus:"",
    loadRoomListStatus: "",
    isShowShopPopup: false,
    isLogin: false,
    shopInfo: {},
    shopList: [],
    liveList: [],
    searchKey: "",
    isShowRoomListPopup: false,
    roomList: [],
    currChooseLiveItem:{},
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    utils.checkEnvConfig(options.env);
    this._envConfig = wx.getStorageSync('envConfig');
    this._opts = options;
    this._userSecret = wx.getStorageSync('userSecret');

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this._page = 1;
    this._reviewPage = 1;
    this._shopPage = 1;
    let isLogin = wx.getStorageSync('token');
    let shopInfo = wx.getStorageSync('shopInfo');
    console.log("shopInfo", shopInfo);
    this.setData({
      liveList: [],
      isLogin: isLogin,
      shopInfo: shopInfo
    }, () => {
      if (isLogin) {
        this._getLiveList();
      }
    });

  },


  jumpToAuth() {
    utils.jumpToAuth('/pages/index/index')
  },

  //微信一键授权手机验证码
  bindGetphonenumber: function (e) {
    console.log("bindGetphonenumber", e)
    if (e.detail.errMsg.indexOf("deny") === -1) {
      utils.post('liveApplet/authMobileLogin', {
        encryptedData: e.detail.encryptedData,
        iv: e.detail.iv,
        sessionKey: this._userSecret.sessionKey,
        openId: this._userSecret.openId,
      }).then(res => {
        if (res.loginToken) {
          utils.setStorage("token", res.loginToken);
          this.setData({
            isLogin: true
          });
        }
        if (res.companyInfo) {
          utils.setStorage("shopInfo", res.companyInfo);
          this.setData({
            shopInfo: res.companyInfo
          });
        }
        this.onShow()
      }).catch((res) => {
        let msg = res.data.msg || '服务器繁忙，请稍后重试！';
        wx.showToast({
          title: msg
        });
      });
    }
  },
  onScrollToLower() {
    if (this.data.loadStatus == 'loading' || this.data.loadStatus == 'end') return;
    this._page++;
    this._getLiveList();
  },

  onScrollToLowerRoomList() {
    if (this.data.loadRoomListStatus == 'loading' || this.data.loadRoomListStatus == 'end') return;
    this._reviewPage++;
    this._getReviewList();
  },

  openRoomList() {
    this._getReviewList();
  },
  _getReviewList() {
    this.setData({
      loadRoomListStatus: "loading",
    })
    let sendData = {
      page: this._reviewPage,
      limit: PAGE_SIZE
    }
    wx.request({
      url: this._envConfig.apiUrl + `live/livePersonal/getPlayBackList/${this._roomListId}`,
      data: sendData,
      dataType: "json",
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Authorization': 'Bearer ' + this.data.shopInfo.apiToken
      },
      method: "GET",
      success: (res) => {
        //token 存在 还返回1002，这个时候就要强制

        let data = res.data.data.data || [];
        console.log(data);
        if (data.length == 0 && this._reviewPage == 1) {
          this.setData({
            loadRoomListStatus: "none",
          })
        } else if (data.length < PAGE_SIZE) {
          this.setData({
            loadRoomListStatus: "end",
          })
        } else {
          this.setData({
            loadRoomListStatus: ""
          })
        }
        this.data.roomList = this.data.roomList.concat(data);
        this.setData({
          roomList: this.data.roomList
        });
      },
      fail: function (res) {
        console.warn("调用失败", res)
        this.setData({
          loadStatus: ""
        })
      }
    })
  },
  searchInput(e) {
    this.setData({
      searchKey: e.detail.value
    });
    if (!e.detail.value.replace(/^\s*(.*?)\s*$/g, "$1")) {
      this.setData({
        liveList: [],
      }, () => {
        this._page = 1;
        this._getLiveList();
      })
    }
  },
  searchConfirm(e) {
    if (this.data.searchKey.replace(/^\s*(.*?)\s*$/g, "$1")) {
      this.setData({
        liveList: []
      });
      this._page = 1;
      this._getLiveList();
    } else {
      wx.showToast({
        title: '请输入搜索的内容',
        icon: "none"
      })
    }

  },
  changeTab(e) {
    let type = e.currentTarget.dataset.type;
    this.setData({
      tabIndex: type
    })
  },
  openShopPopup() {
    this._shopPage=1;
    this.setData({
      shopList:[],
      isShowShopPopup: true
    },()=>{
      this.getShopList();
    });
   

  },
  //获取店铺的列表
  getShopList() {
    utils.get('liveApplet/getCompanyList', {
      page: this._shopPage,
      limit: PAGE_SIZE
    }).then((res) => {
      let data = res || [];
      if (res.length == 0 && this._shopPage == 1) {
        this.setData({
          loadShopStatus: "none",
        })
      } else if (data.length < PAGE_SIZE) {
        this.setData({
          loadShopStatus: "end",
        })
      } else {
        this.setData({
          loadShopStatus: ""
        })
      }
      this.data.shopList = this.data.shopList.concat(data);
      this.setData({
        shopList:  this.data.shopList
      });
    })
  },
  chooseShop(e) {
    let item = e.currentTarget.dataset.item;
    console.log("item", item);
    if (item.apiToken) utils.setStorage("shopInfo", item);
    utils.post("liveApplet/setLoginFlag", {
      userId: item.userId,
      apiToken: item.apiToken
    }).then(res => {
      this.setData({
        shopInfo: item,
        liveList: [],
        isShowShopPopup: false
      }, () => {
        this._page = 1;
        this._getLiveList();
      })
    })
  },

  _getLiveList() {
    this.setData({
      loadStatus: "loading",
    })
    let sendData = {
      page: this._page,
      limit: PAGE_SIZE
    }
    if (this.data.searchKey) {
      sendData.liveName = this.data.searchKey
    }
    wx.request({
      url: this._envConfig.apiUrl + 'liveApplet/getLiveList',
      data: sendData,
      dataType: "json",
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Authorization': 'Bearer ' + this.data.shopInfo.apiToken
      },
      method: "GET",
      success: (res) => {
        //token 存在 还返回1002，这个时候就要强制
        
        if(res.data.statusCode != 200){
          this.setData({
            isLogin:false
          })
          return;
        }
        let data = res.data.data.data || [];
        console.log(data);
        if (data.length == 0 && this._page == 1) {
          this.setData({
            loadStatus: "none",
          })
        } else if (data.length < PAGE_SIZE) {
          this.setData({
            loadStatus: "end",
          })
        } else {
          this.setData({
            loadStatus: ""
          })
        }
        this.data.liveList = this.data.liveList.concat(data);
        this.setData({
          liveList: this.data.liveList
        });
      },
      fail: function (res) {
        console.warn("调用失败", res)
        this.setData({
          loadStatus: ""
        })
      }
    })
  },
  //店铺
  onScrollToLowerShop() {
    console.log("onScrollToLowerShop");
    if (this.data.loadShopStatus == 'loading' || this.data.loadShopStatus == 'end') return;
    this._shopPage++;
    this.getShopList();
  },

  checkJump(e) {
    let item = e.currentTarget.dataset.item;
    let jumpData = {
      liveId: item.id,
      socialRoomId: item.socialRoomId
    }
    if (item.mdType == 2) {
      if (item.status == 1) {
        jumpData.detailId = item.detailId;
        this.jumpToLiveRoom(jumpData)
      } else {
        this._roomListId = item.id;
        this._roomListSocialRoomId = item.socialRoomId;
        this._reviewPage = 1;
        this.setData({
          currChooseLiveItem:item,
          roomList: [],
          isShowRoomListPopup: true
        })
      }
    } else {
      this.jumpToLiveRoom(jumpData)
    }
  },
  roomJump(e) {
    let item = e.currentTarget.dataset.item;
    let data = {
      liveId: this._roomListId,
      socialRoomId: this._roomListSocialRoomId,
      detailId: item.detailId
    }
    if(item.relateId){
      data.relateId = item.relateId;
    }
    console.log("item", data)
    this.jumpToLiveRoom(data);
  },
  jumpToLiveRoom(data) {
    let url = `/pages/plugin-live/index?token=${this.data.shopInfo.apiToken}&liveId=${data.liveId}&socialRoomId=${data.socialRoomId}&env=${this._envConfig.env}`;
    if (data.detailId) {
      url += `&detailId=${data.detailId}`;
    }
    if (data.relateId) {
      url += `&detailId=${data.relateId}`;
    }
    wx.navigateTo({
      url: url
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})